# -*- coding: utf-8 -*-
from flask import jsonify, g, render_template, request
import math
from sqlalchemy.ext.declarative import DeclarativeMeta
import decimal, datetime
from config.dingtalk_setting import AppKey, AppSecret
import json, requests
from datetime import date, datetime, timedelta



def dateafter(num):
    now = datetime.now()
    delta = timedelta(days=num)
    n_days_after = now + delta
    return format(n_days_after.strftime('%Y-%m-%d'))

def datebefore(num):
    now = datetime.now()
    delta = timedelta(days=num)
    n_days_forward = now - delta
    return format(n_days_forward.strftime('%Y-%m-%d'))

def dicgetkey(val,dic):
    for key, value in dic.items():
         if val == value:
             return key

# 钉钉api
def dingtalkpost(url, content):
    token_params = {
        'appkey': AppKey,
        'appsecret': AppSecret,
    }
    dd_token = 'https://oapi.dingtalk.com/gettoken'
    token_response = requests.get(dd_token, params=token_params)  # 向API发起GET请求
    tokenData = token_response.json()
    access_token = tokenData['access_token']

    url = url + '?access_token=' + access_token
    content1=json.dumps(content)
    userid_response = requests.post(url, data=content1)  # 向API发起GET请求
    resdata = userid_response.json()
    return resdata


# 计算年龄
def getage(id_card):
    if id_card:
        birth_year = int(id_card[6:10])
        today_year = datetime.today().year

        how_old = today_year - birth_year
        return how_old
    else:
        return 0


# vue日期时间转换
def datetimetran(time):
    utc_data = time
    t = utc_data[:-5]
    utc_date = datetime.strptime(t, "%Y-%m-%dT%H:%M:%S")
    return utc_date


# 计算输入日期到现在间隔几年几月几日
def handle_data(date):
    if date != 'None':
        end_date = datetime.now()
        start_date = datetime.strptime(date, '%Y-%m-%d')

        e_y = end_date.year
        e_m = end_date.month
        e_d = end_date.day

        s_y = start_date.year
        s_m = start_date.month
        s_d = start_date.day

        diff_y = e_y - s_y
        diff_m = e_m - s_m
        diff_d = e_d - s_d

        diff_info = diff_y * 12 + diff_m + (decimal.Decimal(str(diff_d)) / decimal.Decimal('31'))
        # print('相差月份数: %s' %(diff_info))

        info = divmod(diff_info, 12)
        y_cnt = int(info[0])
        m_cnt = int(math.modf(info[1])[1])
        d_cnt = (decimal.Decimal(str(math.modf(info[1])[0])) * decimal.Decimal('31')).quantize(decimal.Decimal('0'))
        out = '%s年%s月%s天' % (y_cnt, m_cnt, d_cnt)
        return out,y_cnt,m_cnt
    else:
        return 0,0,0


# 去重
def unduplicate(result, data):
    if data not in result:
        result = result + [data]
    return result


def ops_render(template, context={}):
    if 'current_user' in g:
        context['current_user'] = g.current_user
    return render_template(template, **context)


def ops_renderJSON(code=200, msg="操作成功~~", data={}):
    resp = {"code": code, "msg": msg, "data": data}
    return jsonify(resp)


def ops_renderErrJSON(msg="系统繁忙，请稍后再试~~", data={}):
    return ops_renderJSON(code=-1, msg=msg, data=data)


def iPagenation(params):
    total_count = int(params['total_count'])
    page_size = int(params['page_size'])
    page = int(params['page'])

    total_pages = math.ceil(total_count / page_size)
    total_pages = total_pages if total_pages > 0 else 1

    is_prev = 0 if page <= 1 else 1
    is_next = 0 if page >= total_pages else 1
    pages = {
        'current': page,
        'total_pages': total_pages,
        'total': total_count,
        'page_size': page_size,
        'is_next': is_next,
        'is_prev': is_prev,
        'range': range(1, total_pages + 1),
        'url': params['url']
    }

    return pages


# def page(listdatadone):
#     # 分页
#     req = request.values
#     page = 1
#     if 'p' in req and req['p']:
#         page = int(req['p'])
#
#     page_params = {
#         'total_count': listdatadone.count(),
#         "page_size": 30,
#         'page': page,
#         'url': "/?"
#     }
#     pages = iPagenation(page_params)
#     # 0 - 30,30 - 60 ,60 - 90
#     offset = (page - 1) * page_params['page_size']
#     limit = page * page_params['page_size']
#     listdatadone = listdatadone[offset:limit]
#     return pages,listdatadone

class AlchemyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            # an SQLAlchemy class
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
                data = obj.__getattribute__(field)
                try:
                    json.dumps(data)  # this will fail on non-encodable values, like other classes
                    fields[field] = data
                except TypeError:  # 添加了对datetime的处理
                    if isinstance(data, datetime.datetime):
                        fields[field] = data.isoformat()
                    elif isinstance(data, datetime.date):
                        fields[field] = data.isoformat()
                    elif isinstance(data, datetime.timedelta):
                        fields[field] = (datetime.datetime.min + data).time().isoformat()
                    else:
                        fields[field] = None
            # a json-encodable dict
            return fields

        return json.JSONEncoder.default(self, obj)
